package com.nf.nf.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.nf.nf.common.base.BaseController;
import com.nf.nf.common.core.Constants;
import com.nf.nf.common.support.ApiData;
import com.nf.nf.model.*;
import com.nf.nf.service.TbSysLogService;
import com.nf.nf.service.TbSysUserService;
import com.nf.nf.util.IPUtil;
import com.nf.nf.util.IdGen;
import com.nf.nf.util.MD5Tools;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
/**
 * @Author: cris
 * @Description: 登陆接口控制器
 * @Date 2018/11/27 19:58
 * @ClassName: LoginController
 */
@Api(value = "登陆接口", description = "登陆接口")
@RestController
@RequestMapping("")
public class LoginController extends BaseController {
    @Resource
    private TbSysUserService loginService;

    @Resource
    private TbSysLogService logService;

    @Value("${SESSION_TIME}")
    private String sessionTime;

    /**
     * @methodName: loginout
     * @description: 退出登录接口
     * <br/>
      * @param
     * @return com.nf.nf.common.support.ApiData
     * @author cris
     * @date 2018/11/27 19:54
     */
    @PostMapping(value = "loginout")
    @ApiOperation(value = "登出接口", httpMethod = "POST", notes = "登出接口")
    public ApiData loginout() {
        String token = this.getRequestToken();
        if (StringUtils.isEmpty(token)) {
            return new ApiData(0, "退出失败", null);
        }
        TbSysUser user = getUser();
        if (null == user ) {
            return new ApiData(0, "退出失败", null);
        }
        user.setToken("");
        boolean result = loginService.updateById(user);
        if (result) {
            return new ApiData(1, "退出成功", null);
        } else {
            return new ApiData(0, "退出失败", null);
        }
    }

    /**
     * @methodName: login
     * @description: 登陆接口
     * <br/>
      * @param login
     * @param req
     * @return com.nf.nf.common.support.ApiData
     * @author cris
     * @date 2018/11/27 19:53
     */
    @ApiOperation(value = "登陆接口", httpMethod = "POST")
    @PostMapping(value = { "dologin" })
    public ApiData login(@RequestBody Login login, HttpServletRequest req){
        ApiData data = new ApiData();
        String userName = login.getAccount();
        String pwd = login.getPassword();
        TbSysUser usertk = new TbSysUser();
        usertk.setLoginName(userName);
        TbSysUser user = loginService.getOne(new QueryWrapper<TbSysUser>(usertk));
        // 判断用户是否存在
        if (user == null) {
            return getFailApiData("用户不存在！");
        } else if (1 == user.getDelFlag()) {
            return getFailApiData("该用户已删除!");
        } else if (null != user.getEnable() && "0".equals(user.getEnable())) {
            return getFailApiData("该用户已禁用!");
        }
        // 密码校验
        if (!MD5Tools.encodePassword(pwd, user.getSalt()).equals(user.getPassword().toLowerCase())) {
            return getFailApiData("密码不正确!");
        }
        String token = IdGen.uuid();
        token = token + (System.currentTimeMillis() + Integer.valueOf(sessionTime).intValue() * 60000);
        user.setToken(token);
        // 登录之后将信息放进session里面
        HttpSession session = req.getSession();
        session.setAttribute("username", user.getRealName());
        session.setAttribute("id", user.getId());
        boolean result = loginService.updateById(user);

        data.setMsg("登录成功!");
        if ("123456".equals(pwd)) {
            data.setMsg("登录成功！当前密码是默认密码，请尽快修改！");
        }


        String description = "登录系统";
        String ip = IPUtil.getClinetIpByReq(req);
        TbSysLog log = new TbSysLog();
        log.setDescription(description);
        log.setCreateBy(user.getId());
        log.setModuleName(Constants.menuLogin);

        log.setCreateTime(new Date());
        log.setId(IdGen.uuid());
        log.setRequestIp(ip);
        // 保存数据库
        logService.save(log);

        data.setResult(result ? 1 : 0);
        user.setSalt(null);
        user.setPassword(null);
        data.setData(user);
        return data;
    }

    /**
     * @methodName: modifyPwd
     * @description: 修改密码
     * <br/>
      * @param mpd
     * @return com.nf.nf.common.support.ApiData
     * @author cris
     * @date 2018/11/27 19:53
     */
    @ApiOperation(value = "修改密码")
    @PostMapping(value = { "modifyPwd" })
    public ApiData modifyPwd(@RequestBody ModifyPwdDto mpd ) {
        ApiData data = getSuccessApiData();
        TbSysUser user = this.getUser();
        String salt = user.getSalt();
        // pwdOld原始密码
        String pwdOld = mpd.getPwdOld();
        String pwdMd50 = MD5Tools.encodePassword(pwdOld, salt);
        if (!pwdMd50.equals(user.getPassword())) {
            return getFailApiData("原始密码不正确!");
        }
        // 新密码
        String pwdNew = mpd.getPwdNew();
        String pwdMd5 = MD5Tools.encodePassword(pwdNew, salt);
        user.setPassword(pwdMd5);
        user.setSalt(salt);
        user.setToken("");
        boolean result = loginService.updateById(user);
        if (result) {
            data.setMsg("修改成功!");
            data.setResult(1);
        } else {
            data.setMsg("修改失败!");
            data.setResult(0);
        }
        return data;
    }

    /**
     * @methodName: resetPwd
     * @description: 重置密码
     * <br/>
      * @param resetPwdDto
     * @return com.nf.nf.common.support.ApiData
     * @author cris
     * @date 2018/11/27 19:59
     */
    @ApiOperation(value = "重置密码")
    @PostMapping(value = { "resetpwd" })
    public ApiData resetPwd(@RequestBody ResetPwdDto resetPwdDto) {
        ApiData data = getSuccessApiData();
        String id = resetPwdDto.getId();
        TbSysUser user = new TbSysUser();
        user.setId(id);
        TbSysUser desUser = loginService.getById(id);
        String pwdMd5 = MD5Tools.encodePassword(Constants.PASSWORD, desUser.getSalt());
        user.setPassword(pwdMd5);
        user.setToken("");
        user.setSalt(desUser.getSalt());
        boolean result = loginService.updateById(user);
        if (result) {
            data.setMsg("密码重置成功，重置密码为:123456");
            data.setResult(1);
        } else {
            data.setMsg("密码重置失败，请稍后重试!");
            data.setResult(0);
        }
        return data;
    }

}
